package com.bz.xtcx.manager.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Properties;

import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import com.bz.xtcx.manager.vo.VoResponse;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class MyFileUtil {
	
	//private String tomcatPath = "/root/tomcat-8990/webapps/jmrhupload";
	//private String WinPath = "C:/Users/zhangkj/Pictures/jmrhupload";
	//private String tomcatAddr = "http://106.14.172.38:8990/jmrhupload";
	
	public String getUniqueFilename(String suffix) {
        long millis = System.currentTimeMillis();
        String randomString = String.format("%d%05d", millis, (int) (Math.random() * 100000));
        return randomString + (suffix != null ? suffix : "");
    }
	
	public VoResponse upload(MultipartFile file, String filePath, String[] suffixNames) {
		VoResponse voRes = new VoResponse();
		if (file.isEmpty()) {
			voRes.setFail(voRes);
			voRes.setData("文件为空");
			return voRes;
		}
	
		String fileName = file.getOriginalFilename();
		String suffixName = fileName.substring(fileName.lastIndexOf("."));
		
		boolean flag = false;
		for(String s : suffixNames) {
			if(s.equals(suffixName)) {
				flag = true;
			}
		}
		if(!flag) {
			voRes.setFail(voRes);
			voRes.setData("暂不支持文件类型" + suffixName);
			return voRes;
		}

		fileName = this.getUniqueFilename(suffixName);
		boolean result = this.copy(file, filePath, fileName);
		if(!result) {
			voRes.setFail(voRes);
			voRes.setMessage("上传失败");
		}else {
			voRes.setData(fileName);
		}
		return voRes;
	}
	
	public boolean copy(MultipartFile file, String filePath, String fileName) {
		File dest = new File(filePath + fileName);
		if (!dest.getParentFile().exists()) {
			dest.getParentFile().mkdirs();
		}
		try {
			file.transferTo(dest);
			return true;
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 对字节数组字符串进行Base64解码并生成图片
	 * @param imgStr
	 * @param imgFilePath
	 * @return
	 */
	public boolean GenerateImage(String imgStr, String imgFilePath) {
        if (imgStr == null) // 图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        OutputStream out = null;
        try {
            // Base64解码
        	//imgStr.replace("data:image/png;base64,", "");
            byte[] bytes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            out = new FileOutputStream(imgFilePath);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
        	e.printStackTrace();
            return false;
        } finally {
	    	if (out != null) {
	    		try {
	    			out.close();
	    		} catch (IOException e) {
	    			e.printStackTrace();
	    		}
            }
	    }
    }
	
	public String getImageFile(String imgFilePath){
		byte[] data = null;
		//读取图片字节数组
		try {
			InputStream in = new FileInputStream(imgFilePath);
			data = new byte[in.available()];
			in.read(data);
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		//对字节数组Base64编码
		BASE64Encoder encoder = new BASE64Encoder();
		//返回Base64编码过得字节数组字符串
		return encoder.encode(data);
	}
	
	public boolean delFile(String filePath) {
		
		File file = new File(filePath);
	    if (file.exists()) {
	    	return file.delete();
	    }
		return false;
	}
	
	/**
	 * 
	 * @param strfile
	 * @param filePath
	 * @param suffixNames {".jpg", ".jpeg", ".png"}
	 * @return
	 */
	public VoResponse upload2(String strfile, String filePath, String[] suffixNames) {
		VoResponse voRes = new VoResponse();
		if (StringUtils.isEmpty(strfile)) {
			voRes.setFail(voRes);
			voRes.setData("文件为空");
			return voRes;
		}
		//System.out.println("strfile=" + strfile);
		String suffixName = "";
		String imgStr = null;
		try {
			//data:image/png;base64,...
			//data%3Aimage%2Fpng%3Bbase64%2CiVBORw0K
			strfile = URLDecoder.decode(strfile, "utf-8");
			String [] ss = strfile.split(";base64,");
			suffixName = "." + ss[0].replace("data:image/", "");
			imgStr = ss[1];
		}catch(Exception e) {
			e.printStackTrace();
			voRes.setFail(voRes);
			voRes.setData("解码文件后缀异常");
			return voRes;
		}
		boolean flag = false;
		for(String s : suffixNames) {
			if(s.equals(suffixName)) {
				flag = true;
			}
		}
		if(!flag) {
			voRes.setFail(voRes);
			voRes.setData("暂不支持文件类型" + suffixName);
			return voRes;
		}
		String fileName = this.getUniqueFilename(suffixName);
		//String filePath = tomcatPath + "/user/";

		boolean result = this.GenerateImage(imgStr, filePath + fileName);
		if(!result) {
			voRes.setFail(voRes);
			voRes.setMessage("上传失败");
			return voRes;
		}
		voRes.setData(fileName);
		return voRes;
	}
	
	public VoResponse download(String fileName, String filePath, HttpServletResponse response) {
		VoResponse voRes = new VoResponse();
		if (fileName != null) {
			//String filePath = this.getTomcatPath() + "/download/";
			//String filePath = "D:\\01项目\\05XTCX\\";
			//String filePath = this.getTomcatPath() + type;
			File file = new File(filePath, fileName);
			if (file.exists()) {
			    response.setCharacterEncoding("utf-8");
			    response.setContentType("multipart/form-data");
			    String name = null;
				try {
					name = new String(fileName.getBytes(),"ISO8859-1");//解决文件名中文乱码
				} catch (UnsupportedEncodingException e1) {
					e1.printStackTrace();
				}
			    response.setHeader("Content-Disposition", "attachment;fileName=" +  name);
			    InputStream is = null;
	    		OutputStream os = null;
			    try {
			        is = new FileInputStream(filePath + fileName);
			        os = response.getOutputStream();
			        byte[] b = new byte[2048];
			        int length;
			        while ((length = is.read(b)) > 0) {
			            os.write(b, 0, length);
			        }
			        os.close();
			        is.close();
			        return null;
			    }catch (Exception e){
			        e.printStackTrace();
			    }finally {
			    	if (is != null) {
			    		try {
			    			is.close();
			    		} catch (IOException e) {
			    			e.printStackTrace();
			    		}
		            }
			    	if (os != null) {
			    		try {
			    			os.close();
			    		} catch (IOException e) {
			    			e.printStackTrace();
			    		}
		            }
			    }
			}
		}
		voRes.setFail(voRes);
		return voRes;
	}

	public boolean isOSLinux() {
        Properties prop = System.getProperties();

        String os = prop.getProperty("os.name");
        System.out.println(os);
        if (os != null && os.toLowerCase().indexOf("linux") > -1) {
            return true;
        } else {
            return false;
        }
    } 

	public static void main(String[] args) {
		MyFileUtil util = new MyFileUtil();
		System.out.println(util.isOSLinux());
		//System.out.println(util.getImageFile("d://153412663228562941.png"));
	}

}
